package com.atguigu.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.constant.KafkaConstant;
import com.atguigu.constant.RedisConstant;
import com.atguigu.entity.UserInfo;
import com.atguigu.login.TingShuLogin;
import com.atguigu.result.RetVal;
import com.atguigu.service.KafkaService;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.AuthContextHolder;
import com.atguigu.vo.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author Joe
 * @since 2024-11-14
 */
@RestController
@RequestMapping("/api/user/wxLogin")
public class WxLogInController {
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaService kafkaService;
    @Operation(summary = "小程序授权登录")
    @GetMapping("/wxLogin/{code}")
    public RetVal wxLogin(@PathVariable String code) throws Exception {
        //0.获取用户的OpenId
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openId = sessionInfo.getOpenid();
        //1.从数据库中查询用户信息是否存在
        //QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getWxOpenId,openId);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        //1.1认证失败，不存在，往数据库添加
        if(null == userInfo){
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openId);
            userInfo.setNickname("听友"+System.currentTimeMillis());
            userInfo.setAvatarUrl("https://sky-take-out-spikejoe.oss-cn-beijing.aliyuncs.com/95ba3291034437e525cd225aaa71142ae8277778.jpg");
            userInfo.setIsVip(0);//默认非VIP
            userInfoService.save(userInfo);
            kafkaService.sendMessage(KafkaConstant.USER_REGISTER_QUEUE,userInfo.getId().toString());
        }
        //1.2认证成功，存在，往redis存储用户信息
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String userKey = RedisConstant.USER_LOGIN_KEY_PREFIX+uuid;
        redisTemplate.opsForValue().set(userKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);



        HashMap<String, Object> retMap = new HashMap<>();
        retMap.put("token",uuid);
        return RetVal.ok(retMap);
    }

    @TingShuLogin
    @Operation(summary = "获取用户个人信息")
    @GetMapping("/getUserInfo")
    public RetVal getUserInfo(){
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return RetVal.ok(userInfoVo);
    }
}
